package com.example.mypplication.component


import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.ViewCompat

class HeaderCardBehavior(context: Context, attrs: AttributeSet) :
    CoordinatorLayout.Behavior<View>(context, attrs) {

    private var initialY = 0f

    override fun onLayoutChild(
        parent: CoordinatorLayout,
        child: View,
        layoutDirection: Int
    ): Boolean {
        initialY = child.y
        return super.onLayoutChild(parent, child, layoutDirection)
    }

    override fun onStartNestedScroll(
        coordinatorLayout: CoordinatorLayout,
        child: View,
        directTargetChild: View,
        target: View,
        axes: Int,
        type: Int
    ): Boolean {
        return axes == ViewCompat.SCROLL_AXIS_VERTICAL
    }

    override fun onNestedPreScroll(
        coordinatorLayout: CoordinatorLayout,
        child: View,
        target: View,
        dx: Int,
        dy: Int,
        consumed: IntArray,
        type: Int
    ) {
        if (dy > 0) { // 上滑
            val newY = child.y - dy
            if (newY > -child.height) {
                child.y = newY
                consumed[1] = dy
            } else {
                child.y = -child.height.toFloat()
                consumed[1] = (child.y + child.height).toInt()
            }
        } else if (dy < 0) { // 下滑
            if (child.y < initialY) {
                val newY = child.y - dy
                if (newY < initialY) {
                    child.y = newY
                    consumed[1] = dy
                } else {
                    child.y = initialY
                    consumed[1] = (initialY - child.y).toInt()
                }
            }
        }
    }
}